﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Verifications.vers
{
    public class TDMSAnalyzer
    {
        static string testxml = @"F:\20210701_青山项目\转换器相关\HT(霍塔)NVH_20220331\reilhofer XML\reilhofer XML\DF727A56-Gear 1 Coast-20220120 173048025.xml";


        class KeyValue
        {
            public string key;
            public string value;
            public KeyValue() { }
            public KeyValue(string key, string value) { this.key = key; this.value = value; }

            public override string ToString()
            {
                return value.Length > 100 ? $"{key}: {value.Substring(0, 100)}..." : $"{key}: {value}";
            }
        }



        public static void test1()
        {
            testxml = @"F:\20210701_青山项目\转换器相关\HT(霍塔)NVH_20220331\reilhofer XML\reilhofer XML\DF727A56-Gear 7 Coast-20220120 173257489.xml";
            ReadFile(testxml);

            var line = new string('-', 80);
            foreach (var xmlfile in Directory.GetFiles(Path.GetDirectoryName(testxml)))
            {
                if (xmlfile.ToLower().EndsWith(".xml"))
                {
                    Console.WriteLine(line);
                    Console.WriteLine(xmlfile);
                    Console.WriteLine(line);
                    ReadFile(xmlfile);
                    Console.WriteLine(line + "\n\n");
                }
            }
        }

        static void ReadFile(string xmlfile)
        {
            // https://www.cnblogs.com/likui-bookHouse/p/11132756.html
            XmlDocument root = new XmlDocument();
            root.Load(xmlfile);

            //XmlNodeList xnl = root.SelectNodes("/NVH2XML/TestItem/Loadsteps/Loadstep/MeasurementChannels/MeasurementChannel");
            //foreach (XmlNode xn in xnl)
            //{
            //    Console.WriteLine(new String('-', 80));
            //    Console.WriteLine(xn.Name);
            //    Console.WriteLine("[Attributes]");
            //    foreach (XmlAttribute attr in xn.Attributes)
            //        Console.WriteLine($"   {attr.Name}: {attr.Value}");

            //    Console.WriteLine("\n[Child Nodes]");
            //    foreach (XmlNode node in xn.ChildNodes)
            //    {
            //        Console.WriteLine($"   {node.Name}: {node.Value}");
            //    }
            //}


            var TestIem = root.SelectSingleNode("/NVH2XML/TestItem");
            var TestBenchId = TestIem.SelectSingleNode("TestBenchId").InnerText;  // 检测台架的编号
            var K1001 = TestIem.SelectSingleNode("TestItemName").InnerText; // 箱体的版本（型号）
            var K1003 = "终检";
            var K1206 = "霍塔终检台";
            var K0014 = TestIem.SelectSingleNode("SerialNumber").InnerText; // 箱体的编码

            var Loadstep = root.SelectSingleNode("/NVH2XML/TestItem/Loadsteps/Loadstep");
            var K0004 = Loadstep.SelectSingleNode("StartTime").InnerText;

            var LineRangeDefinition = root.SelectNodes("//LineRangeDefinition");
            Console.WriteLine(LineRangeDefinition.Count);


            /*
                <Name>7st Gear H1</Name>
                <Mode>Line</Mode>
                <TestResult>TestIO</TestResult>
                <From>46</From>
                <QI>22</QI>
                <Energy>0.25228309631348</Energy>
                <UpperThreshold>1.11</UpperThreshold>
             */

            // 被测参数与测量值
            foreach (XmlNode node in LineRangeDefinition)
            {
                Console.WriteLine("LineRangeDefinition");
                Console.WriteLine("  Name: " + node.SelectSingleNode("Name").InnerText);
                Console.WriteLine("  Mode: " + node.SelectSingleNode("Mode").InnerText);
                Console.WriteLine("  TestResult: " + node.SelectSingleNode("TestResult").InnerText);
                Console.WriteLine("  From: " + GetNodeText(node, "From"));
                Console.WriteLine("  QI: " + node.SelectSingleNode("QI").InnerText);
                Console.WriteLine("  Energy: " + node.SelectSingleNode("Energy").InnerText);
                Console.WriteLine("  UpperThreshold: " + node.SelectSingleNode("UpperThreshold").InnerText);
                /* LineRangeDefinition 测量信息
                   Name：测量项目，如1st Gear H1 （对应文件霍塔EOL-NVH下线检测技术要求中名称）
                   From：设定值 如 14
                   QI：测试结果，如 30
                   UpperThreshold：上限百分比，如 0.87
                   测量值：等于 QI*UpperThrehold， 如 30 * 0.87 = 26.1
                          若QI得值小于100即合格。
                 */
                var K2001 = node.SelectSingleNode("Name").InnerText;
                var K2110 = "0";
                var K2111 = GetNodeText(node, "From");
                K2111 = K2111.Length == 0 ? "0" : K2111;

                var QI = float.Parse(node.SelectSingleNode("QI").InnerText);
                var UpperThreshold = float.Parse(node.SelectSingleNode("UpperThreshold").InnerText);
                var K0001 = (QI * UpperThreshold).ToString();

            }
            Console.WriteLine("done");
        }

        public static string GetNodeText(XmlNode node, string path)
        {
            var n = node.SelectSingleNode(path);
            return n == null ? "" : n.InnerText;
        }

        public static void test3()
        {
            Console.WriteLine("Hello World!");

            var bts = Convert.FromBase64String("m04k31AUQ9E=");
            foreach (byte item in bts)
            {
                Console.WriteLine(item.ToString("X2"));
            }

            for (int i = 0, len = bts.Length / 2; i < len; i++)
            {
                var v1 = "0x" + bts[i * 2 + 1].ToString("X2") + bts[i * 2].ToString("X2");
                Console.Write(v1);

                //var v2 = short.Parse(v1);
                //Console.WriteLine(v2);
                var v2 = (bts[i * 2 + 1] * 256 + bts[i * 2]);
                v2 = v2 > 32767 ? v2 - 65536 : v2;
                Console.WriteLine(" -> " + v2);
            }


            // <MeasurementChannel

            // 读取所有的行

            List<KeyValue> kvs = new List<KeyValue>();
            var rows = File.ReadAllLines(testxml);


            for (int i = 0; i < rows.Length; i++)
            {
                string row = rows[i].Trim();
                string key = row.Split('>')[0].Trim('<');
                string value = "";
                if (key.StartsWith("/"))
                    continue;

                var starttag = $"<{key}>";
                var endtag = $"</{key}>";
                bool hasStartTag = row.Contains(starttag);
                bool hasEndTag = row.Contains(endtag);




                // <tag>value</tag> 的形式
                if (hasEndTag)
                    value = row.Replace(starttag, "").Replace(endtag, "").Trim();


                if (hasStartTag)
                    kvs.Add(new KeyValue(key, value));

            }


            List<List<KeyValue>> channels = new List<List<KeyValue>>();
            List<KeyValue> temp = new List<KeyValue>();
            foreach (var item in kvs)
            {
                if (item.key.StartsWith("MeasurementChannel "))
                {
                    if (temp.Count > 0)
                        channels.Add(temp);
                    temp = new List<KeyValue>();
                    Console.WriteLine("-----------------------------");
                }
                Console.WriteLine(item.ToString());
            }


            foreach (var item in channels)
            {
                Console.WriteLine(item.Count);
            }



        }


    }
}
